//
//  WebViewController.m
//  PeiJue
//
//  Created by lxy on 2017/9/21.
//  Copyright © 2017年 lixiya. All rights reserved.
//

#import "WebViewController.h"
#import "XYURLHelper.h"
#import "WebView.h"

//业务字段

@interface WebViewController ()<WebProtocol>
@property (nonatomic, strong) WebView *webView;
@property (nonatomic, strong) UIBarButtonItem *backButtonItem;
@property (nonatomic, strong) UIBarButtonItem *closeButtonItem;
@property (nonatomic,strong) UIProgressView *progressView;

@end

@implementation WebViewController
- (instancetype)initWithURLString:(NSString *)URLString{
    self = [super init];
    if (self) {
        if (isNULLString(URLString)) {
            URLString = @"";
        }
        self.requestURL = [NSURL URLWithString:[XYURLHelper handleUrl:URLString parameters:nil]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.progressView];

    if (self.titleString) {
        self.title = self.titleString;
    }

    [self updateUI];
    [self loadRequestURL:self.requestURL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Privates
- (void)updateUI {
    self.navigationItem.leftBarButtonItems = @[self.backButtonItem, self.closeButtonItem];
}

- (void)loadRequestURL:(NSURL *)URL{
    if (URL) {
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        [self.webView loadRequest:request];
    }
}

- (void)updateNavigationBarWithDictionary:(NSDictionary *)dic{
    if (dic) {
        NSString *pageTitle = dic[@"pageTitle"];
        NSString *btnTitle = @"";
        NSString *buttonColor = @"";
        NSString *buttonClickFunction = @"";
        
        if ([[dic allKeys] containsObject:@"buttonTilte"] && dic[@"buttonTilte"]) {
            btnTitle = dic[@"buttonTilte"];
            
        }else if([[dic allKeys] containsObject:@"buttonColor"] && dic[@"buttonColor"]){
            buttonColor = dic[@"buttonColor"];
        }else if ([[dic allKeys] containsObject:@"buttonClickFunction"] && dic[@"buttonClickFunction"])
            buttonClickFunction = dic[@"buttonClickFunction"];
        
        if (pageTitle && ![pageTitle isEqualToString:@""]) {
            self.title = pageTitle;
        }
    }
}

- (BOOL)isCorrectJumpProcotocolScheme:(NSURL*)URL {
    return NO;
}

#pragma mark - Publics
- (void)reloadWithURLString:(NSString *)URLString{
    NSString *handleUrl = [XYURLHelper handleUrl:URLString parameters:nil];
    self.requestURL = [NSURL URLWithString:handleUrl];
    [self loadRequestURL:self.requestURL];
}


#pragma mark - H5内部新协议
- (void)doWirelessURLSchemeWithURL:(NSURL *)URL{
    //    NSString *scheme = [URL scheme];
    NSURLComponents *componets = [[NSURLComponents alloc] initWithURL:URL resolvingAgainstBaseURL:NO];
    NSString *host = componets.host;
    NSString *path = componets.path;
    NSArray *queryItems = componets.queryItems;
    NSMutableDictionary *params = @{}.mutableCopy;
    
    [queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem *queryItem, NSUInteger idx, BOOL * _Nonnull stop) {
        if (queryItem.name && queryItem.value) {
            params[queryItem.name] = queryItem.value;
        }
    }];
    
    // 业务处理
    
}

#pragma mark - Evnent
- (void)backItemClickEvent:(id)sender{
    if (_webView.canGoBack) {
        [self.view endEditing:YES];
        [_webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)closeBtnClickEvent{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark  - MNWebProtocol
- (void)JSBridgeLoadedFinish{
    [self updateUI];
}

- (void)JSBridgeWithWebTitle:(NSString *)webTitle{
    self.title = webTitle;
}

- (void)JSBridgeWithNewprogress:(CGFloat)newprogress{
    if (newprogress == 1) {
        [self.progressView setProgress:1.0 animated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        });
    }else {
        self.progressView.hidden = NO;
        [self.progressView setProgress:newprogress animated:YES];
    }
}

- (void)JSBridgeWithMessageName:(NSString *)functionName databody:(id)body{
    NSDictionary *bodyDictionary = body;
    if ([functionName isEqualToString:@"getNavigationBarInfo"] && isDictWithCountMoreThan0(bodyDictionary)) {
        [self updateNavigationBarWithDictionary:bodyDictionary];
    }
}

- (void)JSBridgeWithNavigationAction:(WKNavigationAction *)navigationAction
                     decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *URL = navigationAction.request.URL;
    if ([self isCorrectJumpProcotocolScheme:URL]){
        [self doWirelessURLSchemeWithURL:URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
- (void)JSBridgeWithAlertMessage:(NSString *)message completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}
- (void)JSBridgeWithAlertMessage:(NSString *)message resultCompletionHandler:(void (^)(BOOL result))resultCompletionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        resultCompletionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        resultCompletionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    
}
- (void)JSBridgeWithAlertTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入" message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = defaultText;
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}
#pragma mark - Getters
- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, KNavBarHeight, kIphoneWidth,5)];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor whiteColor];
    }
    return _progressView;
}

- (WebView *)webView{
    if (!_webView) {
        _webView = [[WebView alloc] initWithFrame:self.view.bounds delegate:self scriptMessageHandlerNames:[self scriptMessageHandlers]];
        [_webView setOpaque:NO];
        [self.view addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(KNavBarHeight, 0, 0, 0));
        }];
        
        [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        }];
    }
    return _webView;
}

- (UIBarButtonItem *)backButtonItem{
    if (!_backButtonItem) {
        _backButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_return"]
                                                                  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                                           style:UIBarButtonItemStylePlain
                                                          target:self
                                                          action:@selector(backItemClickEvent:)];
    }
    return _backButtonItem;
}

- (UIBarButtonItem *)closeButtonItem{
    if (!_closeButtonItem) {
        _closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBtnClickEvent)];
        [_closeButtonItem setTintColor:[UIColor lightGrayColor]];
    }
    return _closeButtonItem;
}

- (NSArray *)scriptMessageHandlers{
    return @[@"getNavigationBarInfo"];
}

@end
